package tk.chenyilin.client;

import java.io.StringReader;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultListModel;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 用于提取xml中的信息并予以进行操作
 */
public class ExtractInfo {
	Connection connection;
	SAXReader reader = new SAXReader();

	ExtractInfo(Connection connection) {
		this.connection = connection;
	}

	String work(String xml) {
		try {
			Document doc = reader.read(new StringReader(xml));
			Element root = doc.getRootElement();
			String type = root.attributeValue("type"); //提取信息类型
			switch (type) {
			case Connection.LOGIN:	//登录信息
				if (getLoginInfo(root)) {
					return "Login successfully. Hello, "
							+ connection.client.username + "!";
				} else {
					return "Fail to login, maybe there's one the same name as you.";

				}
			case Connection.MESSAGE:	//消息
				return getMessage(root);
			case Connection.USER_LIST:	//用户列表
				return getUserList(root);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	String getUserList(Element root) {
		List<Element> list = root.elements("user");
		connection.model = new DefaultListModel<>();
		for (Element user : list) {
			String username = user.getText();
			connection.model.addElement(username);
			connection.chat.jList1.setModel(connection.model);
		}
		return null;
	}

	boolean getLoginInfo(Element root) {
		String response = root.elementText("response");
		switch (response) {
		case "success":
			return true;
		}
		return false;
	}

	@SuppressWarnings("deprecation")
	String getMessage(Element root) {
		String message = root.elementText("message");
		String username = root.elementText("user");
		return username + "  (" + new Date().toLocaleString() + ")\r\n"
				+ message + "\r\n";
	}
}
